import requests
import os

BASE_API = os.getenv("BASE_API", "http://widechaos.cn/api/quant")
ADMIN_TOKEN = os.getenv("QUANT_ADMIN_TOKEN", "")

def _headers():
    return {"Authorization": f"Bearer {ADMIN_TOKEN}"} if ADMIN_TOKEN else {}

def create_token(tunnel_id=None, remark=None):
    data = {}
    if tunnel_id:
        data["tunnelId"] = tunnel_id
    if remark:
        data["remark"] = remark
    r = requests.post(f"{BASE_API}/admin/token", json=data, headers=_headers(), timeout=10)
    return r.json()

def list_tokens():
    r = requests.get(f"{BASE_API}/admin/tokens", headers=_headers(), timeout=10)
    return r.json()

def delete_token(token):
    r = requests.delete(f"{BASE_API}/admin/token/{token}", headers=_headers(), timeout=10)
    return r.json()

def update_remark(token, remark):
    r = requests.patch(f"{BASE_API}/admin/token/{token}/remark", json={"remark": remark}, headers=_headers(), timeout=10)
    return r.json()

if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        print("usage: token_tool.py [create|list|delete|remark] ...")
        sys.exit(1)
    cmd = sys.argv[1]
    if cmd == "create":
        t = sys.argv[2] if len(sys.argv) > 2 else None
        rmk = sys.argv[3] if len(sys.argv) > 3 else None
        print(create_token(t, rmk))
    elif cmd == "list":
        print(list_tokens())
    elif cmd == "delete":
        tok = sys.argv[2]
        print(delete_token(tok))
    elif cmd == "remark":
        tok = sys.argv[2]
        rmk = sys.argv[3]
        print(update_remark(tok, rmk))
    else:
        print("unknown command")